﻿using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ValueGeneration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace M.ValueGenerated
{
    /// <summary>
    /// 自动生成Id
    /// </summary>
    public class UserIdGenerator : ValueGenerator<string>
    {
        public override bool GeneratesTemporaryValues => false;

        /// <summary>
        /// Get current account number from table and increment by 1
        /// </summary>
        /// <returns>Next account number or recycle back to first alpha number</returns>
        private string NextUserId()
        {
            // 该序列号生成器，当天生成的前几位是一致的
            var tempGuid = Guid.NewGuid();
            var bytes = tempGuid.ToByteArray();
            var time = DateTime.Now;
            bytes[3] = (byte)time.Year;
            bytes[2] = (byte)time.Month;
            bytes[1] = (byte)time.Day;
            bytes[0] = (byte)10;
            bytes[5] = (byte)10;
            bytes[4] = (byte)10;
            string s = (new Guid(bytes)).ToString("N");
            /*
            生成的guid：
                e801020a0a0a4a0194c97c4463aafb7a
                e801020a0a0a4cb0b0c6fa58d2cc6c9a
            */
            return s;
        }

        /// <summary>
        /// Template method to perform value generation for AccountNumber.
        /// </summary>
        /// <param name="entry">In this case Customer</param>
        /// <returns>Current account number</returns>
        public override string Next(EntityEntry entry) => NextUserId();
        /// <summary>
        /// Gets a value to be assigned to AccountNumber property
        /// </summary>
        /// <param name="entry">In this case Customer</param>
        /// <returns>Current account number</returns>
        protected override object NextValue(EntityEntry entry) => NextUserId();
    }
}
